#include <stdio.h>
#include <string.h>
#include <assert.h>

char* replaceSpace(char* s){
	if (NULL == s){     //如果S指向空或者为空串
		return NULL;
	}
	int length = strlen(s);

	int count = 0;
	for (int i = 0; i < length; i++){
		if (s[i] == ' '){
			count++;          //统计字符串空格数
		}
	}
	if (!count){              //如果没有空格
		return s;
	}
	int newlen = count * 2 + length;       //计算替换后的新长度
	char* str = (char*)malloc(sizeof(char)*(newlen + 1));     //申请新数组
	if (NULL == str){
		assert(0);
		return NULL;
	}
	int newend = newlen - 1;
	//从后往前替换
	while (length){
		length--;
		if (s[length] == ' '){        //替换空格
			str[newend--] = '0';
			str[newend--] = '2';
			str[newend--] = '%';
		}
		else{
			str[newend--] = s[length];
		}

	}
	str[newlen] = '\0';
	free(s);       //释放旧数组
	return str;
}

int main()
{
	char s[18] = { "We are happy." };
	replaceSpace(s);
	return 0;
}
